package com.hzp.net.netty.server.handler.custom;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * 自定义协议编码
 */
public class CustomEncoder extends MessageToByteEncoder<CustomProtocol> {

    @Override
    protected void encode(ChannelHandlerContext ctx, CustomProtocol protocol, ByteBuf out) throws Exception {
        byte protocolType = protocol.getProtocolType();
        int length = protocol.getBodyLength();
        byte[] body = protocol.getBody();
        out.writeByte(protocolType);
        out.writeInt(length);
        if (length > 0) {
            out.writeBytes(body);
        }
    }
}
